<!--
 * @Author: Haochen
 * @Date: 2021-12-07 17:37:29
 * @LastEditTime: 2021-12-26 15:31:47
 * @FilePath: \recipes-admin-system\src\views\meals\Meals.vue
-->
<template>
  <div class="meals-container">
    <bread-crumb></bread-crumb>

    <div class="search-area">
      <el-input type="text" v-model="searchValue"> </el-input>
      <el-button type="primary" @click="searchMeal">搜索</el-button>

      <el-button type="primary" @click="openAddDialog">
        <i class="el-icon-circle-plus-outline"></i> 添加
      </el-button>
    </div>

    <el-table
      :data="mealsByPage"
      border
      style="width: 100%"
      :header-cell-style="rowClass"
      :cell-style="rowClass"
      :stripe="true"
      :highlight-current-row="true"
    >
      <el-table-column label="'套餐编号">
        <template slot-scope="scope">
          <span>{{ scope.row._id.substr(-5) }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="name" label="名称"> </el-table-column>
      <el-table-column prop="normalPrice" label="价格"> </el-table-column>
      <el-table-column prop="salePrice" label="打折价格"> </el-table-column>
      <el-table-column label="套餐时长">
        <template slot-scope="scope">
          <span>{{ scope.row.mouth + '个月' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="225">
        <template slot-scope="scope">
          <el-button size="mini" @click="openMealsDialog(scope.row._id)">
            <i class="el-icon-edit"></i> 修改</el-button
          >

          <el-button
            size="mini"
            type="danger"
            @click="deleteMeal(scope.row._id)"
          >
            <i class="el-icon-circle-close"></i> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      width="500px"
      :append-to-body="true"
      :title="addDialogVisible ? '添加套餐' : '修改套餐'"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
    >
      <el-form :model="newMeal">
        <el-form-item label="套餐名字" :label-width="formLabelWidth">
          <el-input v-model="newMeal.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="套餐时长" :label-width="formLabelWidth">
          <el-select
            style="width: 150px"
            v-model="newMeal.mouth"
            placeholder="请选择多少月"
          >
            <el-option
              v-for="item in 12"
              style="text-align: center"
              :key="item"
              :label="item + '个月'"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="普通价格" :label-width="formLabelWidth">
          <el-input v-model="newMeal.normalPrice" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="打折价格" :label-width="formLabelWidth">
          <el-input v-model="newMeal.salePrice" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否推荐" :label-width="formLabelWidth">
          <div style="width: 300px">
            <el-radio v-model="newMeal.type" :label="1">是</el-radio>
            <el-tooltip
              content="初次添加套餐请选择'是'，后续可更改"
              placement="top"
            >
              <el-radio
                :disabled="addDialogVisible"
                v-model="newMeal.type"
                :label="0"
                >否</el-radio
              >
            </el-tooltip>
          </div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>

        <el-button v-if="mealsDialogVisible" type="primary" @click="updateMeal"
          >确 定</el-button
        >
        <el-button v-else type="primary" @click="addMeal">确 定</el-button>
      </div>
    </el-dialog>

    <pages
      :total="total"
      :currentPage="pageData.currentPage"
      :pageSize="pageData.pageSize"
      @prevPage="prevPage"
      @nextPage="nextPage"
    />
  </div>
</template>

<script>
import Pages from '../../components/common/Pages.vue';
import BreadCrumb from '../../components/common/BreadCrumb.vue';

import bus from '@/utils/bus.js';
import pageMixin from '@/mixins/pageMixin';

import { createNamespacedHelpers } from 'vuex';

const {
  mapActions: mealsActions,
  mapState: mealsState,
  mapMutations: mealsMutations,
  mapGetters: mealsGetters,
} = createNamespacedHelpers('meals');

export default {
  mixins: [pageMixin],
  components: {
    pages: Pages,
    'bread-crumb': BreadCrumb,
  },
  data() {
    return {
      formLabelWidth: '120px',
      searchValue: '',
      mealsDialogVisible: false,
      addDialogVisible: false,
      mealId: '',
      newMeal: {},
    };
  },
  computed: {
    ...mealsState(['meals', 'total', 'pages']),
    ...mealsGetters(['mealsByPage']),
    dialogVisible: {
      get() {
        return this.addDialogVisible || this.mealsDialogVisible;
      },
      set(val) {
        this.addDialogVisible = val;
        this.mealsDialogVisible = val;
      },
    },
  },
  created() {
    this.getAllMeal();

    bus.$on('handleSizeChange', (size) => {
      this.pageData.pageSize = size;
      this.getAllMeal();
    });

    bus.$on('handleCurrentChange', (currentPage) => {
      this.pageData.currentPage = currentPage;
      this.getAllMeal();
    });
  },
  methods: {
    ...mealsActions(['getAllMealAsync', 'getMealByIdAsync']),
    ...mealsMutations(['SET_PAGESIZE', 'SET_CURRENT']),

    async getAllMeal(searchValue) {
      this.getAllMealAsync(searchValue);
      this.SET_PAGESIZE(this.pageData.pageSize);
      this.SET_CURRENT(this.pageData.currentPage);
      //   console.log(this.$store.state);
      //   console.log(this.admins);
    },

    rowClass() {
      return 'text-align:center';
    },
    openAddDialog() {
      this.newMeal = { type: 1 };
      this.addDialogVisible = true;
    },
    async openMealsDialog(id) {
      let res = await this.getMealByIdAsync(id);
      this.newMeal = res[0];
      // console.log(this.newMeal);
      this.mealsDialogVisible = true;
      this.mealId = id;
    },

    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          this.addDialogVisible = false;
          this.mealsDialogVisible = false;
          done();
        })
        .catch((_) => {});
    },

    closeDialog() {
      this.addDialogVisible = false;
      this.mealsDialogVisible = false;
    },

    async addMeal() {
      // console.log(this.newMeal);
      let res = await this.$api.meals.addMeal(this.newMeal);
      console.log(res);
      this.addDialogVisible = false;
      if (res.status === 200) {
        this.$notify({
          title: '成功',
          message: '添加套餐成功',
          type: 'success',
        });
        this.getAllMeal();
      }
    },

    async deleteMeal(id) {
      this.$confirm('此操作将永久删除此套餐, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          let _id = { _id: id };

          let { data: res } = await this.$api.meals.deleteMeal(_id);
          // console.log(res);
          if (res.meta.status === 200) {
            this.$notify({
              title: '成功',
              message: res.meta.msg,
              type: 'success',
            });

            this.getAllMeal();
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },

    async updateMeal() {
      // console.log(this.newMeal);
      let { data: res } = await this.$api.meals.updateMeal(this.newMeal);

      if (res.meta.status === 200) {
        this.$notify({
          title: '成功',
          message: '修改套餐成功',
          type: 'success',
        });

        this.newMeal = {};

        this.mealsDialogVisible = false;
        this.getAllMeal();
      } else {
        this.newMeal = {};

        this.mealsDialogVisible = false;
      }
    },

    searchMeal() {
      this.getAllMeal(this.searchValue);
    },
  },
  watch: {
    pageData: {
      handler(val) {
        this.getAllMeal();
      },
      deep: true,
    },

    // mealsByPage() {
    //   this.getAllMeal();
    // },

    'pageData.pageSize'() {
      this.pageData.currentPage = 1;
      this.getAllMeal();
    },

    searchValue(val) {
      if (!val) {
        this.getAllMeal(val);
      }
    },
  },
};
</script>

<style scoped lang="scss">
// @import '@/assets/sass/common.scss';

a {
  text-decoration: none;
  color: rgb(124, 124, 124);
}

.meals-container {
  width: 100%;
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
  box-sizing: border-box;
  table {
    margin: 20px 0;
    width: 100%;
    text-align: center;
    border: 1px solid #ccc;
    border-collapse: collapse;
    tr td,
    th {
      height: 50px;
      border: 1px solid #ccc;
      img {
        width: 50px;
        height: 50px;
      }
    }
  }
}

.search-area {
  margin-bottom: 30px;
  height: 30px;
  .el-input {
    width: 200px;
    height: 30px;
    margin-right: 10px;
  }
}

.el-input {
  width: 70%;
}
</style>
